import React, { useState, useEffect, useCallback, useRef } from 'react';
import axios from 'axios';
import './chat.css';
import { NavBar, Popup, Space, Toast } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import {
  SmileOutline,
  AddCircleOutline,
  AudioOutline,
  ShopbagOutline,
  FileOutline,
  PayCircleOutline,
  EnvironmentOutline,
  ExclamationTriangleOutline,
  PictureWrongOutline,
  MoreOutline,
  AudioMutedOutline,
  SoundOutline
} from 'antd-mobile-icons';
import { Uploader } from '@nutui/nutui-react';


const ChatAI = () => {
  const navigate = useNavigate();
  const [message, setMessage] = useState('');
  const [messageCount, setMessageCount] = useState(0);
  const [messagePairs, setMessagePairs] = useState([]);
  const [visible5, setVisible5] = useState(false);
  const [visible1, setVisible1] = useState(false);
  const [shuo, setshuo] = useState(false)
  //判断浏览器是否支持语音合成
  const [isSpeechRecognitionsupported, setIsSpeechRecognitionsupported] = useState(false);
  //语音识别是否正在监听
  const [isListening, setIsListening] = useState(false);
  //语音识别案例
  const [recognition, setRecognition] = useState(null);
  const chatContainerRef = useRef(null);

  useEffect(() => {
    //检查是否支持语音识别
    if ('webkitSpeechRecognition' in window || 'speechRecognition' in window) {
      const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
      console.log(SpeechRecognition);

      const newRecognition = new SpeechRecognition();
      newRecognition.lang = 'zh-CN';//设置语言为中文
      newRecognition.continuous = true;//是否连续识别
      newRecognition.interimResults = true;//返回中间结果
      setRecognition(newRecognition);
      setIsSpeechRecognitionsupported(true);
      console.log('Speech recognition supported');
    } else {
      setIsSpeechRecognitionsupported(false);
      console.log('Speech recognition not supported');
    }
    return () => {
      // 清理语音识别资源
      recognition?.abort();
    };
  }, []);

  useEffect(() => {
    if (!recognition) return;
    const onStart = () => {
      console.log('语音识别已启动');
      setIsListening(true);
    };
    const handleEnd = () => {
      console.log('语音识别已停止');
      setIsListening(false);
    };
    const handleError = (event) => {
      console.error('语音识别错误:', event.error);
      if (event.error === 'network') {
        console.error('网络错误，请检查网络连接或权限设置。');
      }
      setIsListening(false);
    };
    const handleResult = (event) => {
      const currentTranscript = Array.from(event.results)
        .map(result => result[0].transcript)
        .join('');
      console.log('当前识别文本', currentTranscript);
      setMessage(currentTranscript);
    };
    recognition.onstart = onStart;
    recognition.onend = handleEnd;
    recognition.onerror = handleError;
    recognition.onresult = handleResult;

    return () => {
      // 清除事件处理函数
      recognition.onstart = null;
      recognition.onend = null;
      recognition.onerror = null;
      recognition.onresult = null;
    };
  }, [recognition]);

  //开始录音
  const startSpeechRecognition = useCallback(() => {
    setshuo(true)
    if (recognition && !isListening) {
      console.log('Starting speech recognition...');
      try {
        recognition.start();
      } catch (error) {
        console.error('Error starting speech recognition:', error);
      }
    }
  }, [recognition, isListening]);
  //结束录音
  const stopSpeechRecognition = useCallback(() => {
    setshuo(false)
    if (recognition && isListening) {
      console.log('Stopping speech recognition...');
      try {
        recognition.stop();
      } catch (error) {
        console.error('Error stopping speech recognition:', error);
      }
    }
  }, [recognition, isListening]);

  // emoji表情相关逻辑
  const emojilist = [
    ['😀', '😁', '😂', '🤣', '😃', '😅', '😆'],
    ['😝', '🤤', '😒', '📐', '😔', '😕', '🙃'],
    ['🤑', '😲', '🙁', '😖', '😟', '😤', '😢'],
    ['😭', '😉', '😊', '😎', '😍', '😘', '😚'],
    ['😱', '😵', '😡', '😠', '😷', '🤒', '🤕'],
  ];

  //获取ai的头像
  const [dian, setDian] = useState('');


  // 监听 messagePairs 的变化
  useEffect(() => {
    console.log("Message pairs:", messagePairs);
  }, [messagePairs]);

  //语音合成
  const speak = useCallback((content) => {
    if ('speechSynthesis' in window && content) {
      const utterance = new SpeechSynthesisUtterance(content);
      utterance.lang = 'zh-CN'; // 设置识别中文
      utterance.pitch = 0.9; // 设置较为柔和的音调 更柔和的音调
      utterance.rate = 0.9; // 减慢语速以增加柔和感 稍微减慢语速
      utterance.volume = 1; // 保持适中的音量 或者稍微降低一点到 0.9
      const voices = window.speechSynthesis.getVoices();// 选择合适的声音（如果有多个声音选项）
      const preferredVoice = voices.find(voice => voice.name.includes('Yaoyao'));
      if (preferredVoice) {
        utterance.voice = preferredVoice;
      }
      window.speechSynthesis.speak(utterance); // 使用语音合成播放   
    } else {
      console.warn('当前浏览器不支持语音合成');
    }
  },
    []
  );
  useEffect(() => {
    // 清理函数：取消所有正在播放的语音
    return () => {
      window.speechSynthesis.cancel();
    };
  }, []);

  //消息的发送
  const sendMessage = async () => {
    try {
      // 发送消息到服务器
      const response = await axios.post('http://localhost:3000/chat', { userInput: message });
      // 处理服务器返回的数据
      const newMessage = response.data.data;
      // 创建新的消息对象
      const newMessagePair = {
        userMessage: message,
        serverReply: newMessage
      };
      // 更新消息对状态
      setMessagePairs(prevPairs => [...prevPairs, newMessagePair]);
      setMessage('');
    } catch (error) {
      console.error('Error sending message:', error);
    }
  };

  //节流是一种控制函数调用频率的技术，确保一个函数不会在短时间内被频繁调用，而是按照设定的时间间隔执行

  // 创建一个节流函数，限制 sendMessage 的调用频率为每秒一次
  const throttle = (func, limit) => {
    let inThrottle;
    return function () {
      const context = this;//保存当前的上下文
      const args = arguments;//保存传递给函数的参数
      if (!inThrottle) {//如果没有正在进行中的节流操作
        func.apply(context, args);//执行传入的函数，并将保存的上下文和参数传递给它
        //定时器
        inThrottle = setTimeout(() =>
          inThrottle = false, //清除节流
          limit);
      }
    }
  };
  // 创建一个handleScroll 函数，限制为每秒最多执行一次
  const throttledSendMessage = throttle(sendMessage, 1000);

  // 处理键盘事件，当按下 Enter 键时发送消息
  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      throttledSendMessage();
    }
  };

  // 返回上一页
  const back = () => {
    navigate(-1);
    setMessagePairs([])
  };

  // 添加表情符号到输入框
  const addEmoji = (emoji) => {
    setMessage((prevMessage) => prevMessage + emoji);
    setMessageCount((prevCount) => prevCount + emoji.length);
  };

  // 图片上传成功的回调函数
  const handleUploadSuccess = (response) => {
    const imageUrl = JSON.parse(response.responseText).path;
    // 创建新的消息对，包括图片链接
    const newMessagePair = {
      userMessage: `Sent image`,
      serverReply: '',
      image: imageUrl, // 添加图片链接
    };
    setMessagePairs(prevPairs => [...prevPairs, newMessagePair]);
    // 关闭弹窗
    setVisible1(false);
  };

  // 图片上传前的过滤器
  const beforeUpload = async (files) => {
    const allowedTypes = ['image/png', 'image/jpeg'];
    const filteredFiles = Array.from(files).filter(file =>
      allowedTypes.includes(file.type)
    );
    return filteredFiles;
  };

  //跳转聊天设置页面
  const right = (
    <div style={{ fontSize: 24 }}>
      <Space style={{ '--gap': '16px' }}>
        <MoreOutline onClick={() => navigate('/chen_ltsz')} />
      </Space>
    </div>
  )

  //复制
  const copy = useCallback((content) => {
    navigator.clipboard.writeText(content).then(() => {
      Toast.show({
        content: '复制成功',
        afterClose: () => {
          console.log('after')
        },
      })
    })
  })

  // 滚动到底部
  useEffect(() => {
    // 当消息更新时滚动到底部
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  }, [message]);  // 每当 message 更新时打印出来

  useEffect(() => {
    // 组件挂载时读取并解析本地存储的数据
    const storedMessagePairs = localStorage.getItem('messagePairs');
    if (storedMessagePairs) {
      setMessagePairs(JSON.parse(storedMessagePairs));
    }
  }, []);

  useEffect(() => {
    // 监听 messagePairs 的变化，并将其保存到 localStorage
    localStorage.setItem('messagePairs', JSON.stringify(messagePairs));
  }, [messagePairs]);


  // 悬浮球的配置
  const floatingBallConfig = {
    offset: {
      right: 20,
      bottom: 20,
    },
    style: {
      '--rv-floating-box-size': '60px',
    },
    adsorb: {
      indent: 0.5, // 滚动缩进比例
      distance: 20, // 近边停靠距离
    },
  };

  // 悬浮球的点击事件
  const handleFloatingBallClick = () => {
    Toast.show('悬浮球被点击了！');
    console.log('球被电击了');
    
    
  };
  return (
    <div className="box">
      {/* 导航栏，显示当前聊天对象的名字 */}
      <NavBar onBack={back} right={right} className='yan'>聊天客服</NavBar>
      {/* 聊天记录区域 */}
      <div className="body-box" ref={chatContainerRef}>
        {messagePairs.map((pair, index) => (
          <div key={index}>
            {/* 用户发出的消息 */}
            <div className="user">
              <div className="right">
                <div>
                  <img src="https://q7.itc.cn/q_70/images03/20240806/92d3001df33d4b56b1a31a08e0b9800b.jpeg" alt="" className='chat_img' />
                </div>
                <div>
                  <span>{new Date().toLocaleString()}</span>
                  <p className="text-box">{pair.userMessage}</p>
                  {pair.image && <img src={pair.image} alt="Sent image" className='chat_img' />}
                </div>
              </div>
            </div>
            {/* 机器人回复的消息 */}
            <div className="robot">
              <div className="right">
                <img src={dian} alt="" className='chat_img' />
                <div>
                  <span>{new Date().toLocaleString()}</span>
                  <p className="text-box"
                    onClick={() => copy(pair.serverReply)}
                  >{pair.serverReply}</p>
                  <SoundOutline onClick={() => speak(pair.serverReply)} />
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
      {/* 底部输入区域 */}
      <div className="bottom-box" style={{ position: "fixed", right: '0', bottom: '0', overflow: 'auto', background: "white", height: "1rem" }}>
        {shuo ? <AudioMutedOutline className='icons' onClick={stopSpeechRecognition} /> : <AudioOutline className='icons' onClick={startSpeechRecognition} />}
        <textarea
          cols='30'
          maxlength="100"
          value={message}
          onKeyDown={handleKeyDown}
          onChange={(e) => {
            setMessage(e.target.value);
            setMessageCount(e.target.value.length);
          }}
        />
        <SmileOutline className='icons' onClick={() => setVisible5(true)} />
        <AddCircleOutline className='icons' onClick={() => setVisible1(true)} />
      </div>
      {/* 表情选择弹窗 */}
      <Popup
        visible={visible5}
        onMaskClick={() => setVisible5(false)}
        bodyStyle={{
          borderTopLeftRadius: '0.3rem',
          borderTopRightRadius: '0.3rem',
          minHeight: '5rem',
        }}
      >
        {emojilist.flat().map((item, index) => (
          <span key={index} className='icons' onClick={() => {
            addEmoji(item);
            setVisible5(false);
          }}>{item}</span>
        ))}
      </Popup>
      {/* 附加选项弹窗 */}
      <Popup
        visible={visible1}
        onMaskClick={() => setVisible1(false)}
        bodyStyle={{
          borderTopLeftRadius: '0.3rem',
          borderTopRightRadius: '0.3rem',
          minHeight: '5rem',
          display: 'flex',
          justifyContent: 'space-around',
          flexWrap: 'wrap',
          alignItems: 'center',
        }}
      >
        <div className='fu'>
          <PhotoO className='icons' />
          <p style={{ marginLeft: '0.1rem', marginTop: '0.1rem' }}>相册</p>
        </div>
        <div className='fu'>
          <PictureWrongOutline className='icon' />
          <p style={{ marginLeft: '0.1rem', marginTop: '0.1rem' }}>拍照</p>
        </div>
        <div className='fu'>
          <FileOutline className='icon' />
          <p style={{ marginLeft: '0.1rem', marginTop: '0.1rem' }}>订单</p>
        </div>
        <div className='fu'>
          <BalanceListO className='icons' />
          <p style={{ marginLeft: '0.1rem', marginTop: '0.1rem' }}>评价</p>
        </div>
        {/* <div className='fu'>
          <Uploader
            beforeUpload={beforeUpload}
            url='http://127.0.0.1:3000/upload'
            onStart={() => console.log('start触发')}
            onChange={(v) => console.log('outer onChange', v)}
            onSuccess={handleUploadSuccess}
            style={{ marginInlineEnd: '10px', marginBottom: '10px' }}
          />
          <p style={{ marginLeft: '0.5rem', marginTop: '0.5rem' }}>图片</p>
        </div>
        <div className='fu'>
          <EnvironmentOutline className='icon' onClick={() => { navigate('/stores') }} />
          <p style={{ marginLeft: '0.5rem', marginTop: '0.5rem' }}>位置</p>
        </div>
        <div className='fu'>
          <ExclamationTriangleOutline className='icon' onClick={() => { navigate('/chen_tousu') }} />
          <p style={{ marginLeft: '0.5rem', marginTop: '0.5rem' }}>投诉</p>
        </div> */}
      </Popup>

    </div>
  );
};

export default ChatAI;